#!/usr/bin/env python3
#
# Copyright (C) 2020-2024 VyOS maintainers and contributors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 or later as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


# - migrate from "service sstp-server" to "vpn sstp"
# - remove primary/secondary identifier from nameserver
# - migrate RADIUS configuration to a more uniform syntax accross the system
#   - authentication radius-server x.x.x.x to authentication radius server x.x.x.x
#   - authentication radius-settings to authentication radius
#   - do not migrate radius server req-limit, use default of unlimited
# - migrate SSL certificate path

import sys

from vyos.configtree import ConfigTree

if len(sys.argv) < 2:
    print("Must specify file name!")
    sys.exit(1)

file_name = sys.argv[1]

with open(file_name, 'r') as f:
    config_file = f.read()

config = ConfigTree(config_file)
old_base = ['service', 'sstp-server']
if not config.exists(old_base):
    # Nothing to do
    sys.exit(0)
else:
    # ensure new base path exists
    if not config.exists(['vpn']):
        config.set(['vpn'])

    new_base = ['vpn', 'sstp']
    # copy entire tree
    config.copy(old_base, new_base)
    config.delete(old_base)

    # migrate DNS servers
    dns_base = new_base + ['network-settings', 'dns-server']
    if config.exists(dns_base):
        if config.exists(dns_base + ['primary-dns']):
            dns = config.return_value(dns_base + ['primary-dns'])
            config.set(new_base + ['network-settings', 'name-server'], value=dns, replace=False)

        if config.exists(dns_base + ['secondary-dns']):
            dns = config.return_value(dns_base + ['secondary-dns'])
            config.set(new_base + ['network-settings', 'name-server'], value=dns, replace=False)

        config.delete(dns_base)


    # migrate radius options - copy subtree
    # thus must happen before migration of the individual RADIUS servers
    old_options = new_base + ['authentication', 'radius-settings']
    if config.exists(old_options):
        new_options = new_base + ['authentication', 'radius']
        config.copy(old_options, new_options)
        config.delete(old_options)

    # migrate radius dynamic author / change of authorisation server
    dae_old = new_base + ['authentication', 'radius', 'dae-server']
    if config.exists(dae_old):
        config.rename(dae_old, 'dynamic-author')
        dae_new = new_base + ['authentication', 'radius', 'dynamic-author']

        if config.exists(dae_new + ['ip-address']):
            config.rename(dae_new + ['ip-address'], 'server')

        if config.exists(dae_new + ['secret']):
            config.rename(dae_new + ['secret'], 'key')


    # migrate radius server
    radius_server = new_base + ['authentication', 'radius-server']
    if config.exists(radius_server):
        for server in config.list_nodes(radius_server):
            base = radius_server + [server]
            new = new_base + ['authentication', 'radius', 'server', server]

            # convert secret to key
            if config.exists(base + ['secret']):
                tmp = config.return_value(base + ['secret'])
                config.set(new + ['key'], value=tmp)

            if config.exists(base + ['fail-time']):
                tmp = config.return_value(base + ['fail-time'])
                config.set(new + ['fail-time'], value=tmp)

        config.set_tag(new_base + ['authentication', 'radius', 'server'])
        config.delete(radius_server)

    # migrate SSL certificates
    old_ssl = new_base + ['sstp-settings']
    new_ssl = new_base + ['ssl']
    config.copy(old_ssl + ['ssl-certs'], new_ssl)
    config.delete(old_ssl)

    if config.exists(new_ssl + ['ca']):
        config.rename(new_ssl + ['ca'], 'ca-cert-file')

    if config.exists(new_ssl + ['server-cert']):
        config.rename(new_ssl + ['server-cert'], 'cert-file')

    if config.exists(new_ssl + ['server-key']):
        config.rename(new_ssl + ['server-key'], 'key-file')

    try:
        with open(file_name, 'w') as f:
            f.write(config.to_string())
    except OSError as e:
        print("Failed to save the modified config: {}".format(e))
        sys.exit(1)
